package org.jchains.receiver;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.jchains.CORBA.PermissionTransferPackage.CPermission;

public class SocketServer extends Thread {

	// private static int port = 4444;
	int maxConnections = 0;
	Receiver _receiver;
	PermissionTransferServant _pts;

	// Listen for incoming connections and handle them
	// public static void main(String[] args) {
	// create_socket_server();
	// }

	int srv_port = 0;

	public SocketServer(PermissionTransferServant pts, Receiver r, int port) {
		this._receiver = r;
		srv_port = port;
		this._pts = pts;
	}

	public void run() {
		int i = 0;
		Socket server;

		try {
			ServerSocket listener = new ServerSocket(srv_port);

			while ((i++ < maxConnections) || (maxConnections == 0)) {
				// doComms connection;
				// System.out.println("socket listen: " + srv_port);
				server = listener.accept();
				doComms conn_c = new doComms(_pts, server, _receiver);
				Thread t = new Thread(conn_c);
				t.start();
			}
		} catch (IOException ioe) {
			System.out.println("IOException on socket listen: " + ioe);
			ioe.printStackTrace();
		}
	}

}

class doComms implements Runnable {
	private Socket server;
	// private String line, input;
	private Receiver receiver;
	PermissionTransferServant _pts;

	doComms(PermissionTransferServant pts, Socket server, Receiver r) {
		this.server = server;
		this.receiver = r;
		this._pts = pts;
	}

	public void run() {

		// input = "";

		try {
			// Get input from the client
			ObjectInputStream ois = new ObjectInputStream(server
					.getInputStream());
			// PrintStream out = new PrintStream(server.getOutputStream());

			boolean runflag = true;
			while (runflag) {// (line = in.readLine()) != null &&
				// !line.equals(".")) {
				try {
					Object o = ois.readObject();
					CPermission p = (CPermission) o;
					_pts.send(0, p);
				} catch (ClassNotFoundException cne) {
					System.out.println("CNE on socket listen: " + cne);
					cne.printStackTrace();
				}
				catch (Throwable e) {
					System.out.println("e:" + e);
				} 

				// input = input + line;
				// out.println("I got:" + p);
			}

			// Now write to the client

			// System.out.println("Overall message is:" + input);
			// out.println("Overall message is:" + input);

			server.close();
		} catch (IOException ioe) {
			System.out.println("IOException on socket listen: " + ioe);
			ioe.printStackTrace();
		}
	}
}
